package org.budo.filestore.tencent.cos;

import java.io.InputStream;

import org.budo.filestore.api.DeleteResponse;
import org.budo.filestore.api.DownloadRequest;
import org.budo.filestore.api.UploadRequest;
import org.budo.filestore.api.UploadResponse;
import org.budo.filestore.impl.DefaultDeleteResponse;
import org.budo.filestore.impl.DefaultUploadResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.UploadPartRequest;
import com.qcloud.cos.model.UploadPartResult;

/**
 * @author lmw
 */
public class TencentCosFileStore extends AbstractTencentCosFileStore {
    private static final Logger log = LoggerFactory.getLogger(TencentCosFileStore.class);

    @Override
    public UploadResponse upload(UploadRequest request) {
        UploadPartRequest uploadPartRequest = new UploadPartRequest();
        uploadPartRequest.setBucketName(this.getBucketName());
        uploadPartRequest.setInputStream(request.getInputStream());

        try {
            UploadPartResult result = this.getCosClient().uploadPart(uploadPartRequest);
            if (log.isDebugEnabled()) {
                log.debug("#39 upload done, result=" + result);
            }
            return new DefaultUploadResponse(true);
        } catch (Throwable e) {
            log.error("#40 upload error, e=" + e, e);
            return new DefaultUploadResponse(false);
        }
    }

    @Override
    public InputStream downloadStream(DownloadRequest request) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(this.getBucketName(), request.getContentUrl());
        COSObject cosObject = this.getCosClient().getObject(getObjectRequest);
        return cosObject.getObjectContent();
    }

    @Override
    public DeleteResponse delete(DownloadRequest request) {
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.getBucketName(), request.getContentUrl());

        try {
            this.getCosClient().deleteObject(deleteObjectRequest);
            return new DefaultDeleteResponse(true);
        } catch (Throwable e) {
            log.error("#64 upload error, e=" + e, e);
            return new DefaultDeleteResponse(false);
        }
    }
}